package cn.mw.cmdb.template.strategy.importexport;

import cn.mw.cmdb.exception.ZabbixResultException;
import cn.mw.cmdb.template.enums.TemplateImportExportTypeEnum;
import cn.mw.cmdb.template.param.MwTemplateConfigurationParam;
import cn.mw.cmdb.template.param.TemplateImportParam;
import cn.mw.cmdb.template.strategy.TemplateImportExportHandler;
import cn.mw.microMonitorCommon.util.ListMapObjUtils;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

/**
 * @description yaml导入导出处理
 */
@Service
@Slf4j
public class TemplateImportExportXmlHandler extends TemplateImportExportHandler {
    @Override
    public TemplateImportExportTypeEnum handlerType() {
        return TemplateImportExportTypeEnum.XML;
    }

    @Override
    public void exportTemplate(MwTemplateConfigurationParam param, HttpServletResponse response) throws Exception {
        //获取ymal信息
        String exportData = getExportData(param);
        if(StringUtils.isEmpty(exportData)){return;}
        exportData = exportData.substring(1,exportData.length()-1);
        //该字符串需要转成对应的yaml文件
        exportTemplateData(response,exportData,"template.xml");
    }

    @Override
    public void importTemplate(MwTemplateConfigurationParam param, MultipartFile file) throws Exception {
        if (file == null || file.isEmpty() || !file.getOriginalFilename().endsWith(".xml")) {
            throw new ZabbixResultException("文件为空或不是 XML 文件");
        }
        String importData = getImportDataInfo(file);
        if(StringUtils.isEmpty(importData)){return;}
        //导入数据
        TemplateImportParam templateImportParam = param.getTemplateImportParam();
        //去除空数据
        Map map = ListMapObjUtils.beanToMap(templateImportParam);
        delMapNullValue(map);
        for (Object key : map.keySet()) {
            TemplateImportParam.ImportRule importRule = (TemplateImportParam.ImportRule) map.get(key);
            Map ruleMap = ListMapObjUtils.beanToMap(importRule);
            delMapNullValue(ruleMap);
            map.put(key,ruleMap);
        }
        importData(importData,TemplateImportExportTypeEnum.XML.getType(), map,param.getServerId());
    }
}
